package com.agent.generator.service;

import com.agent.common.constant.CommonConstants;
import com.agent.generator.entity.GeneratedTask;
import com.agent.generator.external.ApiStrategyFactory;
import com.agent.generator.external.AIGenerationStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * AI生成核心服务
 */
@Slf4j
@Service
public class AIGeneratorService {
    private final ApiStrategyFactory apiStrategyFactory;
    private final FileStorageService fileStorageService;
    private final GeneratedContentService generatedContentService;
    private final GeneratedTaskService generatedTaskService;

    public AIGeneratorService(ApiStrategyFactory apiStrategyFactory,
                              FileStorageService fileStorageService,
                              GeneratedContentService generatedContentService,
                              GeneratedTaskService generatedTaskService) {
        this.apiStrategyFactory = apiStrategyFactory;
        this.fileStorageService = fileStorageService;
        this.generatedContentService = generatedContentService;
        this.generatedTaskService = generatedTaskService;
    }

    /**
     * 处理视频生成任务
     * @param generatedTask 任务对象
     */
    public void processVideoTask(GeneratedTask generatedTask) {
        try {
            // 更新任务状态为处理中
            generatedTaskService.updateTaskStatus(generatedTask.getId(), CommonConstants.TASK_PROCESSING, null, null);

            // 获取API策略
            AIGenerationStrategy strategy = apiStrategyFactory.getStrategy(generatedTask.getModel());

            // 调用外部API生成视频
            String outputUrl = strategy.generateVideo(generatedTask);

            // 下载生成的文件并存储到Cloudflare R2
            String objectKey = fileStorageService.downloadAndStoreFile(
                    outputUrl, generatedTask.getUserId(), "output", "video.mp4");

            // 生成访问URL
            String outputPath = fileStorageService.generateFileUrl(objectKey);

            // 保存生成的文件路径
            generatedTaskService.updateTaskStatus(generatedTask.getId(), CommonConstants.TASK_COMPLETED, outputPath, null);

            // 记录生成内容
            generatedContentService.recordGeneratedContent(
                    generatedTask.getId(),
                    outputPath,
                    CommonConstants.ASSET_VIDEO,
                    "generated_video.mp4"
            );

            log.info("Video task completed: {}", generatedTask.getId());
        } catch (Exception e) {
            log.error("Video task failed: {}", generatedTask.getId(), e);
            generatedTaskService.updateTaskStatus(
                    generatedTask.getId(),
                    CommonConstants.TASK_FAILED,
                    null,
                    e.getMessage()
            );
        }
    }

    /**
     * 处理图片生成任务
     * @param generatedTask 任务对象
     */
    public void processImageTask(GeneratedTask generatedTask) {
        try {
            // 更新任务状态为处理中
            generatedTaskService.updateTaskStatus(generatedTask.getId(), CommonConstants.TASK_PROCESSING, null, null);

            // 获取API策略
            AIGenerationStrategy strategy = apiStrategyFactory.getStrategy(generatedTask.getModel());

            // 调用外部API生成图片
            String outputUrl = strategy.generateImage(generatedTask);

            // 下载生成的文件并存储到Cloudflare R2
            String objectKey = fileStorageService.downloadAndStoreFile(
                    outputUrl, generatedTask.getUserId(), "output", "image.png");

            // 生成访问URL
            String outputPath = fileStorageService.generateFileUrl(objectKey);

            // 保存生成的文件路径
            generatedTaskService.updateTaskStatus(generatedTask.getId(), CommonConstants.TASK_COMPLETED, outputPath, null);

            // 记录生成内容
            generatedContentService.recordGeneratedContent(
                    generatedTask.getId(),
                    outputPath,
                    CommonConstants.ASSET_IMAGE,
                    "generated_image.png"
            );

            log.info("Image task completed: {}", generatedTask.getId());
        } catch (Exception e) {
            log.error("Image task failed: {}", generatedTask.getId(), e);
            generatedTaskService.updateTaskStatus(
                    generatedTask.getId(),
                    CommonConstants.TASK_FAILED,
                    null,
                    e.getMessage()
            );
        }
    }
}